import { computed, nextTick, Ref, ref } from "vue";
import Sortablejs from "sortablejs";
import { cloneDeep } from "lodash";
export default function InitHook(state: { passData: Ref<Array<SuperTable.NestTableColumnItem | SuperTable.TableCoulmnItem>> }) {
  const { passData } = state;
  const puppeteer = ref<Array<SuperTable.NestTableColumnItem | SuperTable.TableCoulmnItem>>([]);
  const fieldTableRef = ref<any>(null);
  const loading = ref<boolean>(false);
  const init = () => {
    puppeteer.value = cloneDeep(passData.value);
    const targetElem = fieldTableRef.value.$el.querySelector(".vxe-table--main-wrapper .vxe-table--body-wrapper.body--wrapper > table > tbody");
    new Sortablejs(targetElem as HTMLElement, {
      forceFallback: false, // 禁用原生拖拽行为
      // ghostClass: "sortable-ghost", // drop placeholder的css类名
      ghostClass: "sortable-ghost", // drop placeholder的css类名
      handle: ".operation-icon",
      //*********  拖拽中的事件 *********
      onMove: function (evt: any) {
        /*
          evt.dragged; // 被拖拽的对象
          evt.draggedRect; // 被拖拽的对象所在区域 {left, top, right, bottom}
          evt.related; // 被替换的对象
          evt.relatedRect; // DOMRect
          evt.willInsertAfter; // 是在被替换对象的前面还是后面
          originalEvent.clientY; // 鼠标的位置
        */
        // 防止改变固定列的位置
        const { related } = evt;
        const tdList = related.querySelectorAll("td");
        const lastTd = tdList[tdList.length - 1];
        const isFixedDom = lastTd.querySelector(".fixed-column");
        // return false 将来取消拖拽;
        if (isFixedDom) return false;
        else true;
      },
      onEnd: (evt: any) => {
        const { oldIndex, newIndex } = evt;
        const targetRow = puppeteer.value.splice(oldIndex, 1)[0];
        puppeteer.value.splice(newIndex, 0, targetRow);
      }
    });
    nextTick(() => {
      fieldTableRef.value.setCheckboxRow(puppeteer.value, false);
      const showField = puppeteer.value.filter((t: any) => t.isShow);
      fieldTableRef.value.setCheckboxRow(showField, true);
    });
  };
  const allLeftFixedCount = computed<number>(() => {
    return puppeteer.value.filter((t: any) => t.fixed === "left").length;
  });
  const allRightFixedCount = computed<number>(() => {
    return puppeteer.value.filter((t: any) => t.fixed === "right").length;
  });
  return {
    fieldTableRef,
    init,
    puppeteer,
    loading,
    allLeftFixedCount,
    allRightFixedCount
  };
}
